//
//  AlbumPickerController.m
//
//  Created by ELC on 2/15/11.
//  Copyright 2011 ELC Technologies. All rights reserved.
//

#import "ELCAlbumPickerController.h"
#import "ELCImagePickerController.h"
#import "ELCAssetTablePicker.h"

@interface ELCAlbumPickerController ()

@property (nonatomic, strong) ALAssetsLibrary *library;

@end

@implementation ELCAlbumPickerController

//Using auto synthesizers

#pragma mark -
#pragma mark View lifecycle
 
- (void)viewDidLoad
{
    [super viewDidLoad];
	
//    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navBarBg@2x.png"] forBarMetrics:UIBarMetricsDefault];
    
    UILabel *chuliLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 20, 100, 30)];
    chuliLabel.text = @"处理中...";
    chuliLabel.textColor = [UIColor whiteColor];
	chuliLabel.textAlignment = NSTextAlignmentCenter;
    chuliLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:18];
    self.navigationItem.titleView = chuliLabel;
//	[self.navigationItem setTitle:@"处理中..."];
  
//    UIButton *cancelButton=[UIButton buttonWithType:UIButtonTypeCustom];
//    cancelButton.frame=CGRectMake(262, 6, 47, 29);
//    [cancelButton addTarget:self.parent action:@selector(cancelImagePicker) forControlEvents:(UIControlEventTouchUpInside)];
//    [cancelButton setTitle:@"取消" forState:UIControlStateNormal];
//    cancelButton.titleLabel.font = [UIFont systemFontOfSize: 14.0];
//    [cancelButton setBackgroundImage:[UIImage imageNamed:@"xiaoshi.png"] forState:UIControlStateNormal];
    
    UIButton *sendBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    sendBtn.frame = CGRectMake(267, 28, 47, 29);;
    [sendBtn setTitle:@"取消" forState:UIControlStateNormal];
    [sendBtn addTarget:self.parent action:@selector(cancelImagePicker) forControlEvents:(UIControlEventTouchUpInside)];
    sendBtn.titleLabel.font = [UIFont systemFontOfSize:17.0];
    
    
    UIBarButtonItem *temporaryBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:sendBtn];
    temporaryBarButtonItem.style = UIBarButtonItemStylePlain;
 
    [self.navigationItem setRightBarButtonItem:temporaryBarButtonItem];
    
    
    NSMutableArray *tempArray = [[NSMutableArray alloc] init];
	self.assetGroups = tempArray;
    
    ALAssetsLibrary *assetLibrary = [[ALAssetsLibrary alloc] init];
    self.library = assetLibrary;

    // Load Albums into assetGroups
    dispatch_async(dispatch_get_main_queue(), ^
    {
        @autoreleasepool {
        
        // Group enumerator Block
            void (^assetGroupEnumerator)(ALAssetsGroup *, BOOL *) = ^(ALAssetsGroup *group, BOOL *stop) 
            {
                
                if (group == nil) {
                    return;
                }
                
                // added fix for camera albums order
                NSString *sGroupPropertyName = (NSString *)[group valueForProperty:ALAssetsGroupPropertyName];
                NSUInteger nType = [[group valueForProperty:ALAssetsGroupPropertyType] intValue];
                
                if ([[sGroupPropertyName lowercaseString] isEqualToString:@"camera roll"] && nType == ALAssetsGroupSavedPhotos) {
                    if([group numberOfAssets] > 0)
                    {
                        [self.assetGroups insertObject:group atIndex:0];
                    }
                }
                else {
                    if([group numberOfAssets] > 0)
                    {
                        [self.assetGroups addObject:group];
                    }
                }

                // Reload albums
                [self performSelectorOnMainThread:@selector(reloadTableView) withObject:nil waitUntilDone:YES];
            };
            
            // Group Enumerator Failure Block
            void (^assetGroupEnumberatorFailure)(NSError *) = ^(NSError *error) {
                
                UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Error" message:[NSString stringWithFormat:@"Album Error: %@ - %@", [error localizedDescription], [error localizedRecoverySuggestion]] delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
                [alert show];
                
                NSLog(@"A problem occured %@", [error description]);	                                 
            };	
                    
            // Enumerate Albums
            [self.library enumerateGroupsWithTypes:ALAssetsGroupAll
                                   usingBlock:assetGroupEnumerator 
                                 failureBlock:assetGroupEnumberatorFailure];
        
        }
    });
}

- (void)reloadTableView
{
    
    NSLog(@"dsfasdfas");
	[self.tableView reloadData];
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {
        
        self.tableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
        
    }
    UILabel *zhaoLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 20, 100, 30)];
    zhaoLabel.text = @"照片";
    zhaoLabel.textColor = [UIColor whiteColor];
	zhaoLabel.textAlignment = NSTextAlignmentCenter;
    zhaoLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:18];
//    [self.navigationItem setTitle:@"照片"];
    self.navigationItem.titleView = zhaoLabel;
}

- (BOOL)shouldSelectAsset:(ELCAsset *)asset previousCount:(NSUInteger)previousCount
{
    return [self.parent shouldSelectAsset:asset previousCount:previousCount];
}

- (void)selectedAssets:(NSArray*)assets
{
	[_parent selectedAssets:assets];
}

#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return [self.assetGroups count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
    // Get count
    ALAssetsGroup *g = (ALAssetsGroup*)[self.assetGroups objectAtIndex:indexPath.row];
    [g setAssetsFilter:[ALAssetsFilter allPhotos]];
    NSInteger gCount = [g numberOfAssets];
    cell.textLabel.font = [UIFont systemFontOfSize:15];
    cell.textLabel.text = [NSString stringWithFormat:@"%@ (%ld)",[g valueForProperty:ALAssetsGroupPropertyName], (long)gCount];
    [cell.imageView setImage:[UIImage imageWithCGImage:[(ALAssetsGroup*)[self.assetGroups objectAtIndex:indexPath.row] posterImage]]];
	[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
	
    return cell;
}

#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //传入顶部title
    UITableViewCell *cell = (UITableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
	ELCAssetTablePicker *picker = [[ELCAssetTablePicker alloc] initWithTitle:cell.textLabel.text];
	picker.parent = self;
    picker.maxPicNum = self.maxPicNum;
    picker.assetGroup = [self.assetGroups objectAtIndex:indexPath.row];
    [picker.assetGroup setAssetsFilter:[ALAssetsFilter allPhotos]];
    
	picker.assetPickerFilterDelegate = self.assetPickerFilterDelegate;
	
	[self.navigationController pushViewController:picker animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	return 57;
}

@end

